package com.sunmouse.toolkit.fragment.home;


import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunmouse.toolkit.adapter.ClassifyAdapter;
import com.sunmouse.toolkit.bean.ClassifyBean;
import com.sunmouse.toolkit.constant.Config;
import com.sunmouse.toolkit.util.IntentUtil;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.ThreadPoolUtils;
import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.bean.PageBean;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.util.PageUtil;
import com.sunmouse.toolkit.util.WXConfig;
import com.sunmouse.toollib.utils.ToastUtils;
import com.sunmouse.toollib.utils.system.PermissionUtil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class MoreFragment extends BaseFragment {


    @BindView(R.id.m_list)
    RecyclerView mList;
    Unbinder unbinder;

    private String reqParam;
    private ArrayList<ClassifyBean> mData;
    private ClassifyAdapter mAdapter;
    private IntentUtil mIntentUtil;


    public MoreFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_more, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void init() {
        super.init();
        this.mIntentUtil = IntentUtil.getInstance(getActivity());
        reqParam = getRequestParam();
        LogUtils.v("--------" + reqParam.toString());

        this.mData = new ArrayList<>();
        this.mAdapter = new ClassifyAdapter(mData, getActivity());
        this.mList.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        this.mList.setAdapter(mAdapter);
        this.mAdapter.setOnSubItemClickListener(mSubItemClickListener);


        loadingData(1);

    }


    @Override
    public void loadingData(int page) {
        ClassifyBean bean;
        bean = new ClassifyBean();
        bean.setName("other");
        bean.setNo(1);
        bean.setSubData(new ArrayList<PageBean>());
        bean.getSubData().add(new PageBean(Config.Id.PAY, -1, "pay"));
        bean.getSubData().add(new PageBean(Config.Id.QR_CODE, PageUtil.Index.QR_CODE, "qrcode"));
        bean.getSubData().add(new PageBean(Config.Id.SOCKET, PageUtil.Index.SOCKET, "socket"));
        mData.add(bean);
        bean = new ClassifyBean();
        bean.setName("Intent");
        bean.setNo(2);
        bean.setSubData(new ArrayList<PageBean>());
        bean.getSubData().add(new PageBean(Config.Id.CALL, "call"));
        bean.getSubData().add(new PageBean(Config.Id.VIEW_MAP, "view Map"));
        bean.getSubData().add(new PageBean(Config.Id.VIEW_WEB, "view Web"));
        bean.getSubData().add(new PageBean(Config.Id.SEND_EMAIL, "send email"));
        bean.getSubData().add(new PageBean(Config.Id.ACCESS_CONTRACT, "access contract"));
        bean.getSubData().add(new PageBean(Config.Id.LAUNCH, "launch"));
        mData.add(bean);
        this.mAdapter.notifyDataSetChanged();
    }


    /**
     * sub item click
     */
    private ClassifyAdapter.OnSubItemClickListener mSubItemClickListener = new ClassifyAdapter.OnSubItemClickListener() {
        @Override
        public void onSubItemClick(int parentPosition, int childPosition) {
            ClassifyBean bean = mData.get(parentPosition);
            int no = bean.getNo();
            //other
            if (no == 1) {
                int subId = bean.getSubData().get(childPosition).getId();
                if (subId == Config.Id.PAY) {
                    h5Pay();
                    return;
                }
                if (subId == Config.Id.QR_CODE) {
                    jump(bean.getSubData().get(childPosition).getPageIndex());
                    return;
                }
                if (subId == Config.Id.SOCKET) {
                    jump(bean.getSubData().get(childPosition).getPageIndex());
                    return;
                }
                return;
            }
            //intent issue
            if (no == 2) {
                int subId = bean.getSubData().get(childPosition).getId();
                switch (subId) {
                    case Config.Id.CALL:
                        mIntentUtil.call("15527825713", subId);
                        break;
                    case Config.Id.VIEW_MAP:
                        mIntentUtil.accessMap("geo:37.422219,-122.08364?z=14", subId);
                        break;
                    case Config.Id.VIEW_WEB:
                        mIntentUtil.accessWeb("https://baidu.com");
                        break;
                    case Config.Id.SEND_EMAIL:
                        mIntentUtil.sendEmail("1746861438@qq.com", "Haha", "I co", "");
                        break;
                    case Config.Id.ACCESS_CONTRACT:
                        mIntentUtil.accessContract(subId);
                        break;
                    case Config.Id.LAUNCH:
                        mIntentUtil.launchTarget("sunmouse.launch");
                        break;
                }
            }
        }
    };


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Config.Id.CALL) {
            if (!PermissionUtil.isCallPermitted(getActivity(), requestCode)) getActivity().finish();
            mIntentUtil.call("15527825713", requestCode);
            return;
        }
        if (requestCode == Config.Id.VIEW_MAP) {
            if (!PermissionUtil.isLocationPermitted(getActivity(), requestCode))
                getActivity().finish();
            mIntentUtil.accessMap("geo:37.422219,-122.08364?z=14", requestCode);
            return;
        }
        if (requestCode == Config.Id.ACCESS_CONTRACT) {
            if (!PermissionUtil.isReadingContractPermitted(getActivity(), requestCode))
                getActivity().finish();
            mIntentUtil.accessContract(requestCode);

            return;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.Id.ACCESS_CONTRACT) {
            if (resultCode == -1) {
                Uri uri = data.getData();
                String[] projection = {Phone.NUMBER};
                Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
                cursor.moveToFirst();
                String number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
                ToastUtils.simpleToast(getActivity(), "your sleect is " + number);
            }
        }
    }

    /**
     * h5 pay
     */
    private void h5Pay() {
        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(WXConfig.REQ_URL);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
                    bw.write(reqParam);
                    bw.flush();
                    bw.close();
                    int status = conn.getResponseCode();
                    if (status == 200) {
//                        conn.setDoInput(true);
                        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String str = "";
                        String result = "";
                        while ((str = br.readLine()) != null) {
                            result += str;
                        }
                        LogUtils.v("-----" + result);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

//        mUtils.post(WXConfig.REQ_URL + "=" + reqParam, null, new StringHttpResponse() {
//            @Override
//            public void onSuccess(String response, String flag) {
//
//            }
//
//            @Override
//            public void onPreExecute(String flag) {
//
//            }
//
//            @Override
//            public void onFailure(Exception e, String flag) {
//
//            }
//        });

    }

    /**
     * get request params
     */
    public String getRequestParam() {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<appid>");
        sb.append("wx2421b1c4370ec43b");
        sb.append("</appid>");

        sb.append("<attach>");
        sb.append("微信支付");
        sb.append("</attach>");

        sb.append("<body>");
        sb.append("测试");
        sb.append("</body>");

        sb.append("<mch_id>");
        sb.append("100000100");
        sb.append("</mch_id>");

        sb.append("<attach>");
        sb.append("wx2421b1c4370ec43b");
        sb.append("</attach>");

        sb.append("<detail>");
        sb.append("<![CDATA[{ \"goods_detail\":[ { \"goods_id\":\"iphone6s_16G\", \"wxpay_goods_id\":\"1001\", \"goods_name\":\"iPhone6s 16G\", \"quantity\":1, \"price\":528800, \"goods_category\":\"123456\", \"body\":\"苹果手机\" }, { \"goods_id\":\"iphone6s_32G\", \"wxpay_goods_id\":\"1002\", \"goods_name\":\"iPhone6s 32G\", \"quantity\":1, \"price\":608800, \"goods_category\":\"123789\", \"body\":\"苹果手机\" } ] }]]>");
        sb.append("</detail>");

        sb.append("<nonce_str>");
        sb.append("1add1a30ac87aa2db72f57a2375d8fec");
        sb.append("</nonce_str>");

        sb.append("<notify_url>");
        sb.append("http://wxpay.wxutil.com/pub_v2/pay/notify.v2.php");
        sb.append("</notify_url>");

        sb.append("<openid>");
        sb.append("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o");
        sb.append("</openid>");

        sb.append("<out_trade_no>");
        sb.append("1415659990");
        sb.append("</out_trade_no>");

        sb.append("<spbill_create_ip>");
        sb.append("14.23.150.211");
        sb.append("</spbill_create_ip>");

        sb.append("<total_fee>");
        sb.append("1");
        sb.append("</total_fee>");

        sb.append("<trade_type>");
        sb.append("JSAPI");
        sb.append("</trade_type>");

        sb.append("<sign>");
        sb.append("0CB01533B8C1EF103065174F50BCA001");
        sb.append("</sign>");
        sb.append("</xml>");

        return sb.toString();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public ArrayList<String> getFunctionItems() {
        ArrayList<String> list = new ArrayList();
        list.add("pay");
        list.add("qrcode");
        list.add("socket");
        return list;
    }
}
